/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : nicepay.js                                 
*  Description  : 결제
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-21  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	
	
	function clsComm()
	{
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){

		}
		// 상세정보
		, getEventInfo: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "DonationDetailView";
			var options = {
				"reserveSeq": arg["예약코드"]
			}
			_gf.ajax({
				"sid": "DR001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "결과값": {}
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					var obj = items;
					
					res["결과값"] = {
						"시작일": _util.nvl(obj["startDt"])
						, "종료일": _util.nvl(obj["endDt"])
						, "당첨자발표일": _util.nvl(obj["publicDate"])
						, "라운드날짜": _util.nvl(obj["reservDate"])
						, "라운드요일": _util.nvl(obj["bookingDay"])
						, "골프장명": _util.nvl(obj["golfClubNm"])
						, "코스명": _util.nvl(obj["courseInfoNm"])
						, "홀": _util.nvl(obj["holeCnt"])
						, "1인그린피": _util.nvl(obj["greenFee"])
						, "티타임": _util.nvl(obj["bookingTime"])
						, "참여인원": _util.nvl(obj["applyCnt"], 0)
						, "총금액": _util.nvl(obj["toTalgreenFee"], 0)
						, "기부금": _util.nvl(obj["donatePrice"], 0)
						, "상태코드": _util.nvl(obj["resrvStatus"])
						, "나의상태": _util.nvl(obj["joinStatus"])
					}
				}
				
				document.objControl.finishEventInfo(res);
			});
		}
		// 해쉬키
		, getHashString: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "setPayData";
			_gf.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, {
				"reserv_seq": arg["예약코드"]
				, "reserv_type": arg["예약타입"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
					, "결과값": {}
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					var obj = items;
					
					res["결과값"] = {
						"mid": _util.nvl(obj["mid"])
						, "mkey": _util.nvl(obj["mkey"])
						, "edidate": _util.nvl(obj["edidate"])
						, "hashcode": _util.nvl(obj["hashcode"])
						, "가격": _util.nvl(obj["price__pay"])
					}
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
		// 자선예약
		, nicepaySubmit: function(arg){
			var thisClass = this;
			
			arg = arg || {};
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "DonationReservApply";
			var options = {
				
			}
			
			for(var k in arg){
				if(k == "콜백") continue;
				
				options[k] = arg[k];
			}
			_gf.ajax({
				"sid": "DR001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			}, true);
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		
		this.q_reserve = null;
		this.openerControl = null;
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			this.q_reserve = _util.getParam("q_reserve");
			
			if(opener){
				if(opener.document.objControl){
					this.openerControl = opener.document.objControl;
				}
			}
			
			if(!this.openerControl){
				self.close();
				return;
			}
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return _gf.getMyInfoData();
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			
		}
		, _start: function(){
			var thisClass = this;
			
			this.objComm.getEventInfo({
				"예약코드": this.q_reserve
				, "콜백": function(ret){
					thisClass.finishEventInfo(ret);
				}
			});
		}
		// 자선예약정보 완료
		, finishEventInfo: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisClass = this;
			
			var $f = $("form");
			var d = ret["결과값"];
			var mi = _gf.getMyInfoData();
			
//			var d1 = new Date();
//			d1.setDate(d1.getDate()+1);
//			
//			var VbankExpDate = d1.getFullYear() + ("00" + (d1.getMonth()+1)).substrEx(-2) + ("00" + d1.getDate()).substrEx(-2);
//			
//			var d2 = new Date();
//			var EdiDate = d2.getFullYear() + ("00" + (d2.getMonth()+1)).substrEx(-2) + ("00" + d2.getDate()).substrEx(-2) + ("00" + d2.getHours()).substrEx(-2) + ("00" + d2.getMinutes()).substrEx(-2) + ("00" + d2.getSeconds()).substrEx(-2);
//			
//			
//			// 상점서명키 (꼭 해당 상점키로 바꿔주세요)
//			//var merchantKey = "9Kc7DtzESexzL67a0lu3lwZUc/adl072nYiYk5kX0mm24oxYbKxbxHalWLXL8g15cSnXfi060Vf0zYKKqDPOqQ==";
//			var merchantKey = "33F49GnCMS1mFYlGXisbUDzVf2ATWCl9k3R++d5hDd3Frmuos/XLx8XhXpe+LDYAbpGKZYSwtlyyLOtS/8aD7A==";
//			// 상점 MID
//			//var merchantID = "sky720000";
//			var merchantID = "nictest00m";
//			
//			var md_src = EdiDate + merchantID + d["기부금"] + merchantKey;
			
			this.objComm.getHashString({
				"예약코드": this.q_reserve
				, "예약타입": "E"
				, "콜백": function(ret){
					thisClass.finishHashString(ret);
				}
			});
			
			$f.append('<input type="hidden" name="selectType" value="">');
			$f.append('<input type="hidden" name="TransType" value="0">');
			$f.append('<input type="hidden" name="GoodsName" value="골프인 자선예약">');
			$f.append('<input type="hidden" name="Amt" value="">');
			$f.append('<input type="hidden" name="Moid" value="' + this.q_reserve + '">');
			$f.append('<input type="hidden" name="BuyerName" value="' + mi["이름"] + '">');
			$f.append('<input type="hidden" name="BuyerEmail" value="' + mi["이메일"] + '">');
			$f.append('<input type="hidden" name="BuyerTel" value="' + mi["휴대폰"].replace(/\-/g, "") + '">');
			$f.append('<input type="hidden" name="MID" value="">');
			$f.append('<input type="hidden" name="SkinType" value="blue">');
			$f.append('<input type="hidden" name="GoodsCl" value="0">');
			$f.append('<input type="hidden" name="GoodsCl" value="0">');
			$f.append('<input type="hidden" name="PayMethod" value="CARD,CELLPHONE">');
			$f.append('<input type="hidden" name="GoodsCnt" value="1">');
			$f.append('<input type="hidden" name="ParentEmail" value="">');
			$f.append('<input type="hidden" name="BuyerAddr" value="">');
			$f.append('<input type="hidden" name="BuyerPostNo" value="">');
			$f.append('<input type="hidden" name="UserIP" value="' + _ip + '">');
			$f.append('<input type="hidden" name="MallIP" value="192.168.0.82">');
			$f.append('<input type="hidden" name="ProxyFrameURL" value="">');
			$f.append('<input type="hidden" name="TransType" value="0">');
			$f.append('<input type="hidden" name="OptionList" value="0">');
			$f.append('<input type="hidden" name="VbankExpDate" value="">');
			$f.append('<input type="hidden" name="MallUserID" value="">');
			$f.append('<input type="hidden" name="SUB_ID" value="">');
			$f.append('<input type="hidden" name="BuyerAuthNum" value="">');
			$f.append('<input type="hidden" name="MallUserID" value="">');
			$f.append('<input type="hidden" name="EncodeParameters" value="CardNo,CardExpire,CardPwd">');
			$f.append('<input type="hidden" name="EdiDate" value="">');
			$f.append('<input type="hidden" name="EncryptData" value="">');
			$f.append('<input type="hidden" name="SocketYN" value="Y">');
			$f.append('<input type="hidden" name="TrKey" value="">');
		}
		// 해쉬키 완료
		, finishHashString: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
			var $f = $("form");
			var d = ret["결과값"];
			
			$f.find("input[name='MID']").val(d["mid"]);
			$f.find("input[name='EdiDate']").val(d["edidate"]);
			$f.find("input[name='EncryptData']").val(d["hashcode"]);
			$f.find("input[name='Amt']").val(d["가격"]);
			
			setTimeout(function(){
				goPay($f.get(0));
			}, 1000);
		}
		// 결제요청 완료
		, finishNicepaySubmit: function(ret){
			//if(ret["메시지"]) alert(ret["메시지"]);
			//if(ret["결과코드"] != "00000") return;
			
			alert(ret["결과코드"]);
			
//			this.openerControl.closeNicepay(self, ret);
//			self.close();
		}
		// 결제요청
		, nicepaySubmit: function(){
			var thisClass = this;
			var $f = $("form");
			
			var op = {
				"reservseq": this.q_reserve
				, "콜백": function(ret){
					thisClass.finishNicepaySubmit(ret);
				}
			}
			
			$f.find("select").each(function(){
				op[$(this).attr("name").toLowerCase()] = $(this).find("option:selected").val();
			});
			
			$f.find("input").each(function(){
				var t = $(this).attr("type").toUpperCase();
				
				switch(t){
					case "radio":
					case "checkbox":
						if($(this).prop("checked")) op[$(this).attr("name").toLowerCase()] = $(this).val();
						break;
					default:
						op[$(this).attr("name").toLowerCase()] = $(this).val();
						break;
				}
			});
			
			this.objComm.nicepaySubmit(op);
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});